//
//  HMStatusPictureView.swift
//  WeiBo
//
//  Created by Apple on 16/9/22.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SDWebImage

//  重用标记
private let HMStatusPictureViewCellIdentifier = "HMStatusPictureViewCellIdentifier"
//  每项之间的间距
private let itemMargin: CGFloat = 5
//  计算每项的宽度， 向上转
private let itemWidth = CGFloat(Int(ScreenWidth - 2 * HMHomeTableViewCellMargin - 2 * itemMargin) / 3)

//  微博首页配图
class HMStatusPictureView: UICollectionView, UICollectionViewDataSource {
    
    var picUrls: [HMStatusPictureInfo]? {
        didSet {
            messageLabel.text = "\(picUrls?.count ?? 0)"
            let calcSize = calcSizeWithCount(count: picUrls?.count ?? 0)
            
            
            
            self.snp_updateConstraints { (make) in
                make.size.equalTo(calcSize)
            }
            self.reloadData()
            
        }
    }

    
    // MARK:    --懒加载
    private lazy var messageLabel: UILabel = UILabel(textColor: UIColor.blue, fontSize: 20)
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        backgroundColor = RandomColor()
        //  注册cell
        register(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureViewCellIdentifier)
        //  设置数据源代理
        dataSource = self
        addSubview(messageLabel)
        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    
    //  根据图片张数计算配图大小
    private func calcSizeWithCount(count: Int) -> CGSize {
        
        if count == 1 {
            //  从缓存中获取图片
            if let url = picUrls?.first?.thumbnail_pic {
                let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: url)
                //  图片下载完成，没有问题
                if image != nil {
                    
                    
//                    var size = image!.size
////                    //  过窄处理
//                    if image!.size.width < 80 {
//                        
//                        let calcWidth: CGFloat = 80
//                        //  不能有小数，有可能超出
//                        let calcHeight = CGFloat(Int(calcWidth / image!.size.width * image!.size.height))
//                        
//                        size.width = calcWidth
//                        size.height = calcHeight
//                    
//                    }
//                    
//                    
//                   
//                    
//                    
//                    //  更新flowlayout的每项的大小
//                    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
//                    flowLayout.itemSize = size
                    
                    
//                    return size
                    
                    //  获取图片后处理大小， 我们这边就处理了 就设置一个固定的大小
                    
                    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                    flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
                    return CGSize(width: itemWidth, height: itemWidth)
                }
                else {
                    //  更新flowlayout的每项的大小
                    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                    flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
                    
                    return CGSize(width: itemWidth, height: itemWidth)
                }
            }
            
        } else {
            
//            if count == 2 {
//            
//            }
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
            
        }
        
        
        
        
        //  计算行数和列数
        let cols = count > 3 ? 3 : count
        let rows = (count - 1) / 3 + 1
        
        if count == 2 {
        
        }
        
        
        let currentWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        let currentHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        
        
        
        return CGSize(width: currentWidth, height: currentHeight)
        
    }
    
    // MARK:    --UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMStatusPictureViewCellIdentifier, for: indexPath) as! HMStatusPictureViewCell
        cell.picUrl = picUrls![indexPath.item]
        
        return cell
    }
    
    
    
    
    
    

}


//  自定义配图cell
class HMStatusPictureViewCell: UICollectionViewCell {
    
    var picUrl: HMStatusPictureInfo? {
        didSet {
            if let url = picUrl?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
            
        }
    }
    
    //  懒加载
    private lazy var imageView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  按照图片原样等比例填充
        view.contentMode = .scaleAspectFill
        //  多余部分剪切
        view.clipsToBounds = true
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //  添加控件设置约束
    private func setupUI() {
        
        contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
        
    }
    
}










